package com.lbssoft.gpsbd.aspect;

import com.lbssoft.datalink.EntityManager;
import com.lbssoft.gpsbd.common.Constant;
import com.lbssoft.gpsbd.common.ErrorEnum;
import com.lbssoft.gpsbd.dao.DeviceMapper;
import com.lbssoft.gpsbd.dao.GeofenceMapper;
import com.lbssoft.gpsbd.dao.GroupMapper;
import com.lbssoft.gpsbd.datalink.Context;
import com.lbssoft.gpsbd.model.Device;
import com.lbssoft.gpsbd.model.Geofence;
import com.lbssoft.gpsbd.model.Group;
import com.lbssoft.gpsbd.model.Result;
import com.lbssoft.gpsbd.model.vo.DeviceGeofencesParam;
import com.lbssoft.gpsbd.model.vo.GeofenceDevicesParam;
import com.lbssoft.gpsbd.model.vo.GroupGeofencesParam;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


@Aspect
@Component
public class SyncRelationAspect {
    //使用org.slf4j.Logger,这是Spring实现日志的方法
    private final static Logger logger = LoggerFactory.getLogger(SyncRelationAspect.class);



    @Autowired
    DeviceMapper deviceMapper;

    @Autowired
    GeofenceMapper geofenceMapper;

    @Autowired
    GroupMapper groupMapper;

    /**
     * 定义AOP扫描路径
     * 第一个注解只扫描aopTest方法
     */
    @Pointcut("execution(public * com.lbssoft.gpsbd.controller.DeviceController.bindGeofences(..)) " +
            "||execution(public * com.lbssoft.gpsbd.controller.DeviceController.unbindGeofences(..))" +
            "||execution(public * com.lbssoft.gpsbd.controller.GeofenceController.bindDevices(..))" +
            "||execution(public * com.lbssoft.gpsbd.controller.GeofenceController.unbindDevices(..))"+
            "||execution(public * com.lbssoft.gpsbd.controller.GroupController.groupBindGeofences(..))"+
            "||execution(public * com.lbssoft.gpsbd.controller.GroupController.groupUnbindGeofences(..))")
    public void relation(){}

    /**
     * 记录HTTP请求开始时的日志
     */
    @Before("relation()")
    public void doBefore(JoinPoint joinPoint){
    }

    /**
     * 记录HTTP请求结束时的日志
     */
    @After("relation()")
    public void doAfter(){
    }

    /**
     * 获取返回内容
     * @param object
     */
    @AfterReturning(returning = "object",pointcut = "relation()")
    public void doAfterReturn(Object object){
    }

    /**
     * 环绕通知（Around advice） ：包围一个连接点的通知，类似Web中Servlet规范中的Filter的doFilter方法。可以在方法的调用前后完成自定义的行为，也可以选择不执行。
     * @param joinPoint
     */
    @Around("relation()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable
    {
        com.lbssoft.datalink.model.Result res = new com.lbssoft.datalink.model.Result();
        Device device;
        DeviceGeofencesParam deviceGeofences;
        GeofenceDevicesParam geofenceDevices;
        GroupGeofencesParam groupGeofences;
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Object[] args = joinPoint.getArgs();
        Method method = signature.getMethod(); //获取被拦截的方法
        String methodName = method.getName(); //获取被拦截的方法名
        //判断是否开启同步
        if (!Constant.DEV_MODE) {
            System.out.println("====同步开始=====");
            switch (methodName) {
                //设备绑定围栏
                case "bindGeofences":
                    deviceGeofences = (DeviceGeofencesParam) args[0];
                    device = deviceMapper.getDeviceById(deviceGeofences.getDeviceId());
                    for(Integer geofenceId:deviceGeofences.getGeofenceIds()){
                        Geofence geofence = geofenceMapper.getInfo(geofenceId);
                        Map<String,Object> param = new HashMap<String,Object>();
                        param.put("deviceUUID",device.getUuid());
                        param.put("geofenceUUID",geofence.getUuid());
                        res  =  Context.entityManager.permission(param,true);
                    }
                    if (res.getCode() != 0) {
                        return new Result(ErrorEnum.E_005.getErrorCode(), ErrorEnum.E_005.getErrorMsg(), "");
                    }
                    break;
                //设备解除绑定围栏
                case "unbindGeofences":
                    deviceGeofences = (DeviceGeofencesParam) args[0];
                    device = deviceMapper.getDeviceById(deviceGeofences.getDeviceId());
                    for(Integer geofenceId:deviceGeofences.getGeofenceIds()){
                        Map<String,Object> param = new HashMap<String,Object>();
                        Geofence geofence = geofenceMapper.getInfo(geofenceId);
                        param.put("deviceUUID",device.getUuid());
                        param.put("geofenceUUID",geofence.getUuid());
                        res  =  Context.entityManager.permission(param,false);
                    }
                    if (res.getCode() != 0) {
                        return new Result(ErrorEnum.E_005.getErrorCode(), ErrorEnum.E_005.getErrorMsg(), "");
                    }
                    break;
                    //围栏绑定设备
                case "bindDevices":
                    geofenceDevices = (GeofenceDevicesParam) args[0];
                    Geofence geofence = geofenceMapper.getInfo(geofenceDevices.getGeofenceId());
                    for(Integer deviceId:geofenceDevices.getDeviceIds()){
                        device = deviceMapper.getDeviceById(deviceId);
                        Map<String,Object> param = new HashMap<String,Object>();
                        param.put("deviceUUID",device.getUuid());
                        param.put("geofenceUUID",geofence.getUuid());
                        res  =  Context.entityManager.permission(param,true);
                    }
                    if (res.getCode() != 0) {
                        return new Result(ErrorEnum.E_005.getErrorCode(), ErrorEnum.E_005.getErrorMsg(), "");
                    }
                    break;
                //围栏解除设备
                case "unbindDevices":
                        geofenceDevices = (GeofenceDevicesParam) args[0];
                    Geofence geofence1 = geofenceMapper.getInfo(geofenceDevices.getGeofenceId());
                    for(Integer deviceId:geofenceDevices.getDeviceIds()){
                        device = deviceMapper.getDeviceById(deviceId);
                        Map<String,Object> param = new HashMap<String,Object>();
                        param.put("deviceUUID",device.getUuid());
                        param.put("geofenceUUID",geofence1.getUuid());
                        res  = Context.entityManager.permission(param,false);
                    }
                    if (res.getCode() != 0) {
                        return new Result(ErrorEnum.E_005.getErrorCode(), ErrorEnum.E_005.getErrorMsg(), "");
                    }
                    break;
                //分组绑定围栏
                case "groupBindGeofences":
                    groupGeofences = (GroupGeofencesParam) args[0];
                     Group group =  groupMapper.getGroupById(groupGeofences.getGroupId());
                    for(Integer geofenceId:groupGeofences.getGeofenceIds()){
                        Map<String,Object> param = new HashMap<String,Object>();
                        Geofence geofence2 = geofenceMapper.getInfo(geofenceId);
                        param.put("groupUUID",group.getUuid());
                        param.put("geofenceUUID",geofence2.getUuid());
                        res  =  Context.entityManager.permission(param,true);
                    }
                    if (res.getCode() != 0) {
                        return new Result(ErrorEnum.E_005.getErrorCode(), ErrorEnum.E_005.getErrorMsg(), "");
                    }
                    break;
                //分组解除绑定围栏
                case "groupUnbindGeofences":
                    groupGeofences = (GroupGeofencesParam) args[0];
                    Group group2 =  groupMapper.getGroupById(groupGeofences.getGroupId());
                    for(Integer geofenceId:groupGeofences.getGeofenceIds()){
                        Map<String,Object> param = new HashMap<String,Object>();
                        Geofence geofence2 = geofenceMapper.getInfo(geofenceId);
                        param.put("groupUUID",group2.getUuid());
                        param.put("geofenceUUID",geofence2.getUuid());
                        res  =  Context.entityManager.permission(param,false);
                    }
                    if (res.getCode() != 0) {
                        return new Result(ErrorEnum.E_005.getErrorCode(), ErrorEnum.E_005.getErrorMsg(), "");
                    }
                    break;
                default:
            }
            System.out.println("=====同步结束=====");
        }


        return  joinPoint.proceed();
    }

}